package com.xiaoguang.selecttextview

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.xiaoguang.selecttext.ItemClickListener
import com.xiaoguang.selecttext.SelectBuilder
import com.xiaoguang.selecttext.OnSelectListener
import com.xiaoguang.selecttext.SelectHelper
import com.xiaoguang.selecttext.SelectWorker
import com.xiaoguang.selecttext.SelectionInfo
import com.zzhoujay.richtext.RichText

/**
 * 消息
 * hxg 2020.9.13 qq:929842234
 */
class MsgAdapter(private val mContext: Context, private val mList: List<MsgBean>) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun getItemViewType(position: Int): Int {
        return mList[position].type
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflate: View = LayoutInflater.from(mContext).inflate(R.layout.item_msg_text, parent, false)
        return ViewHolderText(inflate)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val msgBean = mList[position]
        when (holder) {
            is ViewHolderText -> {
                holder.iv_head_left.visibility = if (msgBean.isReceive) View.VISIBLE else View.GONE
                holder.iv_head_right.visibility = if (msgBean.isReceive) View.GONE else View.VISIBLE
                if (msgBean.isReceive) {
                    setGravity(holder.textView, Gravity.START)
                } else {
                    setGravity(holder.textView, Gravity.END)
                }

                // todo 方法一：富文本  需要转行成富文本形式
                RichText.initCacheDir(holder.textView.context.applicationContext) // 项目里初始化一次即可
                RichText.from(msgBean.content)
                    .autoFix(false) // 是否自动修复宽高，默认true
                    .autoPlay(true) // gif自动播放
                    .singleLoad(false) // RecyclerView里设为false 若同时启动了多个RichText，会并发解析，类似于AsyncTask的executeOnExecutor
                    .done { // 在成功回调处理
                        // 演示消息列表选择文本
                        holder.selectText(msgBean)
                    }
                    .into(holder.textView)

                // todo 方法二：普通文本
                // holder.textView.text = msgBean.content
                // // 演示消息列表选择文本
                // holder.selectText(msgBean)

            }
        }
    }

    // 设置FrameLayout子控件的gravity参数
    private fun setGravity(view: View, gravity: Int) {
        val params = view.layoutParams as FrameLayout.LayoutParams
        params.gravity = gravity
    }

    override fun getItemCount(): Int {
        return mList?.size ?: 0
    }

    ////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////   演示消息列表选择文本 start   ///////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////

    internal inner class ViewHolderText(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val text_rl_container: RelativeLayout
        val iv_head_left: ImageView
        val iv_head_right: ImageView
        val textView: TextView
        private var selectedText: String? = null

        init {
            text_rl_container = itemView.findViewById(R.id.rl_container)
            iv_head_left = itemView.findViewById(R.id.iv_head_left)
            iv_head_right = itemView.findViewById(R.id.iv_head_right)
            textView = itemView.findViewById(R.id.tv_content)
        }

        /**
         * 演示消息列表选择文本
         */
        fun selectText(msgBean: MsgBean) {
            val builder = SelectBuilder(textView) // 放你的textView到这里！！
                .setCursorHandleColor(ContextCompat.getColor(mContext, R.color.colorAccent)) // 游标颜色
                .setCursorHandleSizeInDp(22f) // 游标大小 单位dp
                .setSelectedColor(
                    ContextCompat.getColor(
                        mContext,
                        R.color.colorAccentTransparent
                    )
                ) // 选中文本的颜色
                .setSelectAll(true) // 初次选中是否全选 default true
                .setScrollShow(true) // 滚动时是否继续显示 default true
                .setMagnifierShow(true) // 放大镜 default true
                .setSelectTextLength(2)// 首次选中文本的长度 default 2
                .setPopDelay(100)// 弹窗延迟时间 default 100毫秒

            SelectHelper.push(builder,object : OnSelectListener {

                /**
                 * 选中文本回调
                 */
                override fun onTextSelected(content: CharSequence?) {
                    selectedText = content.toString()
                }

                /**
                 * 全选显示自定义弹窗回调
                 */
                override fun onSelectAllPopShow(anchor: TextView) {
                    Log.d("SelectWorker", "select -- all --- show: ${anchor==textView}")
                    showCustomPop(text_rl_container)
                }

                /**
                 * 解除自定义弹窗回调
                 */
                override fun onSelectAllPopDismiss() {
                    msgPop?.dismiss()
                }

                override fun onSelectPopShow(anchor: TextView,selectionInfo: SelectionInfo) {
                    Log.d("SelectWorker", "select --- show: ${anchor == textView}")
                }

                override fun onSelectPopDismiss() {
                }

                override fun onDestroy() {}

            })

            textView.setOnClickListener {
                SelectHelper.resetSelect(it)
                // 拿原始文本方式
                clickTextView(msgBean.content!!) // 推荐
                // clickTextView(originalContent!!) // 不推荐 富文本可能被修改值 导致gif动不了
            }

            textView.setOnLongClickListener {
                SelectHelper.startSelect(it)
                return@setOnLongClickListener true
            }

        }


        /**
         * 全选
         */
        private fun selectAll() {
            SelectHelper.selectAll(textView)
        }

        /**
         * 转发
         */
        private fun forward() {
            SelectHelper.resetSelect(textView)
            toast(R.string.forward)
        }

        /**
         * 复制
         */
        private fun copy(selectedText: String?) {
            SelectHelper.resetSelect(textView)
            val cm = mContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            cm.setPrimaryClip(ClipData.newPlainText(selectedText, selectedText))
            toast("已复制")
        }

        private var downTime: Long = 0

        /**
         * 双击进入查看内容
         *
         * @param content 内容
         */
        private fun clickTextView(content: CharSequence) {
            if (System.currentTimeMillis() - downTime < 500) {
                downTime = 0
                val dialog = MsgDetailDialog(mContext, content)
                dialog.show()
            } else {
                downTime = System.currentTimeMillis()
            }
        }

        private fun toast(strId: Int) {
            toast(mContext.getString(strId))
        }

        private fun toast(str: String) {
            Toast.makeText(mContext.applicationContext, str, Toast.LENGTH_SHORT).show()
        }

        /**
         * 自定义弹窗
         *
         * @param targetView 目标View
         * @param msgBean    实体
         */
        var msgPop:CustomPop? = null
        private fun showCustomPop(targetView: View) {
            msgPop?.show() ?:run {
                msgPop = CustomPop(mContext, targetView)
                msgPop!!.setItemClickListener(object : ItemClickListener {
                    override fun onClick(operator:Int) {
                        when(operator){
                            R.string.copy ->  copy(selectedText)
                            R.string.rollback -> toast(R.string.rollback)
                            R.string.forward -> forward()
                            R.string.collect ->  toast(R.string.collect)
                            R.string.select -> toast(R.string.select)
                            R.string.quote -> toast(R.string.quote)
                            R.string.delete ->  toast(R.string.delete)
                        }
                    }
                })
                msgPop!!.addItem(R.drawable.ic_msg_copy, R.string.copy)
                msgPop!!.addItem(R.drawable.ic_msg_rollback, R.string.rollback)
                msgPop!!.addItem(R.drawable.ic_msg_forward, R.string.forward)
                msgPop!!.addItem(R.drawable.ic_msg_collect, R.string.collect)
                msgPop!!.addItem(R.drawable.ic_msg_select, R.string.select)
                msgPop!!.addItem(R.drawable.ic_msg_quote, R.string.quote)
                msgPop!!.addItem(R.drawable.ic_msg_delete, R.string.delete)
                // 设置每个item自适应
                // msgPop.setItemWrapContent();
                // 设置背景 和 箭头
                // msgPop.setPopStyle(R.drawable.shape_color_666666_radius_8, R.drawable.ic_arrow_666);
                msgPop!!.show()
            }
        }

    }

}